package com.flying.pas.form.service;

import java.util.List;
import java.util.Map;

import com.flying.common.annotation.DaoCreate;
import com.flying.common.annotation.DaoQuery;
import com.flying.common.annotation.DaoRemove;
import com.flying.common.annotation.DaoUpdate;
import com.flying.common.annotation.Transaction;
import com.flying.common.util.Codes;
import com.flying.common.util.ServiceHelper;
import com.flying.framework.annotation.MethodInfo;
import com.flying.framework.annotation.Param;
import com.flying.framework.annotation.Service;
import com.flying.framework.application.Application;
import com.flying.framework.metadata.Metadata;
import com.flying.framework.model.ActionResult;
import com.flying.framework.model.ModelFactory;
import com.flying.framework.model.QueryResult;
import com.flying.framework.module.LocalModule;
import com.flying.framework.service.AbstractService;
import com.flying.pas.form.model.Action;
import com.flying.pas.form.model.Field;
import com.flying.pas.form.model.Form;

@Service(value="FormService", desc="表单")
public class FormService extends AbstractService{
	private ActionService as;
	private FieldService fs;
    
	public void setActionService(ActionService s) {
		this.as = s;
	}
	
	public void setFieldService(FieldService s) {
		this.fs = s;
	}
	
	@MethodInfo("新增")
	public ActionResult createFromModule(
			@Param(value="source_module", required=true,	desc="模块ID") String moduleId
		) throws Exception {
		LocalModule m = (LocalModule) Application.getInstance().getModules().getLocalModule(moduleId);
		Map<String, Metadata> metas =  m.getMetadataRepository().getRepository();
		for(String sk: metas.keySet()) {
			this.createFromMetadata(moduleId, sk);
		}
		return ModelFactory.create(ActionResult.class, Codes.CODE, Codes.SUCCESS);
	}
	
	@MethodInfo("新增")
	@Transaction
	public Form createFromMetadata(
			@Param(value="source_module", required=true,	desc="模块ID") String moduleId,
			@Param(value="source_meta", required=true,	desc="Meta代码") String meta
		) throws Exception {
		LocalModule m = (LocalModule) Application.getInstance().getModules().getLocalModule(moduleId);
		Metadata metadata = m.getMetadataRepository().getMetadata(meta);
		final String pkStr = metadata.getPrimaryKeys().toString();
		Form form = this.create(meta, metadata.getString("title"), moduleId, metadata.getEntity(), 
				metadata.getTable(), null,pkStr.substring(1, pkStr.length() - 1),
				"Meta:" + meta+"; Table:"+metadata.getTable());
		List<com.flying.framework.metadata.Field> fields = metadata.getFields();
		int order_index = 0;
		for(com.flying.framework.metadata.Field f: fields) {
			order_index ++;
			String title = (String)f.get("title");
			String name = f.getName();
			String data_type = f.getDataType();
			String display_type = f.getType();
			String text_field = f.getTextField();
			String value_field = f.getValueField();
			String ds_url = f.getUrl();
			String ds_module_id = null;
			String ds_service_id = null;
			String ds_query = null;
			Integer condition = f.isCondition()? 1: 0;
			Integer is_column = "false".equalsIgnoreCase((String)f.get("isColumn"))?0:1;
			Integer is_field = "false".equalsIgnoreCase((String)f.get("isField"))?0:1;
			Integer readonly = "true".equalsIgnoreCase((String)f.get("readonly"))?1:0;
			Integer is_required = "true".equalsIgnoreCase((String)f.get("required"))?1:0;
			Integer max_length = (Integer)f.get("maxlength");
			
			this.fs.create(form.getFormId(), title, name, data_type, display_type, 
					order_index, is_column, is_field, readonly, condition, 
					ds_module_id, ds_service_id, ds_query, ds_url, text_field, value_field, 
					is_required, max_length, null, null, null,
					"Field:" + f.getName(), null);
		}
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> buttons = (List<Map<String, Object>>)metadata.getData().get("buttons");
		order_index = 0;
		if(buttons != null) {
			for(Map<String, Object> b: buttons) {
				order_index ++;
				String title = (String)b.get("title");
				String icon_cls = (String)b.get("iconCls");
				String action = (String)b.get("function");
				this.as.create(form.getFormId(), title, icon_cls, action, order_index, null, null);
			}
		}
		return form;
	}
	
	@MethodInfo("新增")
	@DaoCreate(entity=Form.ENTITY_NAME)
	public Form create(
			@Param(value=Form.CODE, required=true,	desc="表单代码") String code,
			@Param(value=Form.NAME, required=false,	desc="名称") String name,
			@Param(value=Form.MODULE, required=false,	desc="所属模块") String module,
			@Param(value=Form.ENTITY, required=false,	desc="实体") String entity,
			
			@Param(value=Form.TABLE_NAME, required=false,	desc="表名") String table_name,
			@Param(value=Form.DATASOURCE, required=false,	desc="数据源") String datasource,
			@Param(value=Form.PK_FIELDS, required=false,	desc="主键") String pk_fields,
			@Param(value=Form.REMARKS, required=false,	desc="说明") String remarks
		) throws Exception {
		return null;
	}

	@MethodInfo("修改")
	@DaoUpdate(entity=Form.ENTITY_NAME)
	public ActionResult update(
			@Param(value=Form.FORM_ID, required=true,	desc="表单ID") Long form_id,
			@Param(value=Form.CODE, required=true,	desc="表单代码") String code,
			@Param(value=Form.NAME, required=false,	desc="名称") String name,
			@Param(value=Form.MODULE, required=false,	desc="所属模块") String module,
			@Param(value=Form.ENTITY, required=false,	desc="所属实体") String entity,
			@Param(value=Form.TABLE_NAME, required=false,	desc="表名") String table_name,
			@Param(value=Form.DATASOURCE, required=false,	desc="数据源") String datasource,
			@Param(value=Form.REMARKS, required=false,	desc="说明") String remarks
		) throws Exception {
		
		return null;
	}

	@MethodInfo("克隆")
	@Transaction
	public Form cloneForm(
			@Param(value=Form.FORM_ID, required=true,	desc="表单ID") Long form_id
		) throws Exception {
		Form of = this.findById(form_id);
		Form nf = this.create(of.getCode()+2, of.getName(), of.getModule(), of.getEntity(), 
				of.getTableName(), of.getDatasource(), of.getPkFields(), of.getRemarks());
		List<Field> ofs = this.fs.findByFormId(form_id).getRows();
		ofs.stream().forEach(x -> {
			x.setFormId(nf.getFormId());
			ServiceHelper.invoke("pas","FieldService:create", x);
		});
		List<Action> oas = this.as.findByFormId(form_id).getRows();
		oas.stream().forEach(x -> {
			x.setFormId(nf.getFormId());
			ServiceHelper.invoke("pas","ActionService:create", x);
		});
		return nf;
	}

	@MethodInfo("删除")
	@Transaction
	@DaoRemove(entity=Form.ENTITY_NAME)
	public ActionResult remove(
			@Param(value=Form.FORM_ID, required=true,	desc="表单ID") Long form_id
		) throws Exception {
		this.as.removeByFormId(form_id);
		this.fs.removeByFormId(form_id);
		return null;
	}

	@MethodInfo("搜索")
	@DaoQuery(entity=Form.ENTITY_NAME, pageable=true, modelClass=Form.class, osql="order by module, code")
	public QueryResult<Form> findAll(
			@Param(value=Form.CODE, required=false,	desc="表单代码", tag="LIKE") String code,
			@Param(value=Form.NAME, required=false,	desc="名称", tag="LIKE") String name,
			@Param(value=Form.MODULE, required=false,	desc="所属模块") String module,
			@Param(value=Form.TABLE_NAME, required=false,	desc="表名", tag="LIKE") String table_name,
			@Param(value=Form.ENTITY, required=false,	desc="所属实体", tag="LIKE") String entity,
			@Param(value=Codes.PAGE_NUM, 	required=false, desc="分页页号，默认0") int page,
			@Param(value=Codes.PAGE_SIZE, 	required=false, desc="分页大小，默认10") int rows) throws Exception {
		return null;
	}

	@MethodInfo("查询")
	@DaoQuery(entity=Form.ENTITY_NAME, single=true, throwsNotFoundException=true )
	public Form findByModuleAndCode(
			@Param(value=Form.MODULE, required=true,	desc="所属模块") String module,
			@Param(value=Form.CODE, required=true,	desc="表单代码") String code
		) throws Exception {
		return null;
	}

	@MethodInfo("查询")
	@DaoQuery(entity=Form.ENTITY_NAME, single=true, throwsNotFoundException=true )
	public Form findById(
			@Param(value=Form.FORM_ID, required=true,	desc="表单ID") Long form_id
		) throws Exception {
		return null;
	}

}